#include "Servo_motor.h"

void Servo_Init_TIM1(uint16_t arr, uint16_t psc)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_OCInitTypeDef TIM_OCInitStructure;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    // RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE);

    // GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3, ENABLE);        // Timer3部分重映射 TIM3_CH2-> PB5

    // 设置该引脚为复用输出功能， 输出TIM3 CH2 的PWM脉冲波形， GPIOA11
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;                   // GPIO A11
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;             // 复用推挽输出
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;           // IO口速率
    GPIO_Init(GPIOA, &GPIO_InitStructure);                      // GPIO初始化

    TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);				// 初始化时基单元默认值
    TIM_TimeBaseStructure.TIM_Period = arr;                         //ARR 设置下一个更新活动的自动冲撞载寄存器
    TIM_TimeBaseStructure.TIM_Prescaler = psc;                      //PSC 预分频
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;                    // 设置时钟分割：TDTS = Tck_tim
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;     // 向上计数
    TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);                 // 时基单元初始化

    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;               // PWM脉冲宽度调制1， 计数值小于自动重载载值时， 输出高电平
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;   // 比较输出使能
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;       // 设置TIM输出极性为高
    TIM_OCInitStructure.TIM_Pulse = 0;		//CCR 设置待装入捕获比较寄存器的脉冲值
    TIM_OC4Init(TIM1, &TIM_OCInitStructure);                        // 根据T指定的参数初始化外设TIM3 OC2

    TIM_OC4PreloadConfig(TIM1, TIM_OCPreload_Enable);

    TIM_Cmd(TIM1, ENABLE);                                          // 主输出使能
    TIM_ARRPreloadConfig(TIM1, ENABLE);
    TIM_CtrlPWMOutputs(TIM1, ENABLE);
}